package ru.zombator.taskman.dbadmin.actions;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;

import ru.zombator.taskman.core.dbclient.DbException;
import ru.zombator.taskman.core.domain.IPerson;
import ru.zombator.taskman.dbadmin.AdminApp;
import ru.zombator.taskman.dbadmin.dialogs.AddEditUserDialog;
import ru.zombator.taskman.dbadmin.dialogs.AddEditUserDialog.Mode;

public class ModifyUserAction extends ASimpleAction {
	private static final String ACTION_ID = "ru.zombator.taskman.dbadmin.modifyUser";
	
	@Override
	public String getId() {
		return ACTION_ID;
	}
	
	public ModifyUserAction(AdminApp mainWindow) {
		super(mainWindow);
	}
	
	@Override
	protected String getImageName() {
		return null;
	}
	
	@Override
	public String getText() {
		return "Изменить...";
	}
	
	@Override
	public void run() {
		AddEditUserDialog dialog = new AddEditUserDialog(mainApp,
				Mode.EDITING);
		if (dialog.open() == IDialogConstants.OK_ID) {
			final String ipAddress = dialog.getIpAddress();
			final String name = dialog.getUserName();
			
			try {
				final IPerson selectedPerson = (IPerson)
					((IStructuredSelection) mainApp.getUsersTable().getSelection()).getFirstElement();

				final IPerson copyPerson = selectedPerson.clone();
				copyPerson.setName(name);
				copyPerson.setIpAddress(ipAddress);				
				new ProgressMonitorDialog(mainApp.getShell()).run(true, false, new IRunnableWithProgress() {
					@Override
					public void run(IProgressMonitor monitor) throws InvocationTargetException,
							InterruptedException {
						SubMonitor subPm = SubMonitor.convert(monitor, IProgressMonitor.UNKNOWN);
						try {
							mainApp.getClient().changeUser(copyPerson);
						} catch (DbException dbe) {
							throw new InvocationTargetException(dbe);
						} finally {
							if (subPm != null)
								subPm.done();
						}
					}
				});
				
				selectedPerson.setName(name);
				selectedPerson.setIpAddress(ipAddress);
				mainApp.getUsersTable().setInput(mainApp.getLocalUserList());
			} catch (InvocationTargetException e) {
				MessageDialog.openError(mainApp.getShell(), "Ошибка",
						e.getCause().getMessage() != null ? e.getCause().getMessage()
								: "Не удалось изменить данные пользователя.");
				return;
			} catch (InterruptedException e) {
				// non-cancelable => это исключение не возникнет
			}
		}		
	}
	
	@Override
	public boolean isEnabled() {
		IStructuredSelection sel = (IStructuredSelection) mainApp.getUsersTable().getSelection();
		return !sel.isEmpty() && sel.size() == 1;
	}	
}